package com.qys.training.biz.alive.listener;

import com.hazelcast.core.*;
import com.qys.training.biz.utils.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author Winstone
 * @date 2020/8/5 - 3:17 下午
 */
public class AliveListener implements MessageListener<String> {
    public static final Logger logger = LoggerFactory.getLogger(AliveListener.class);

    private HazelcastInstance instance;

    public AliveListener(HazelcastInstance instance) {
        this.instance = instance;
    }

    /**
     * 接收alive 心跳
     *
     * @param message
     */
    public void onMessage(Message<String> message) {
        String msg = message.getMessageObject();
        IMap<String, String> map = instance.getMap("aliveMap");
        IMap<String, String> aliveList = instance.getMap("aliveList");

        String timestamp = DateUtil.getTimestamp();

        String aliveCache = map.get(msg);

        if (aliveCache == null || aliveCache.equals("")) {
            logger.info("[{}] online--->{}", msg, new Date().toString());
        }
        map.put(msg, timestamp, 5, TimeUnit.SECONDS);
        aliveList.put(msg, timestamp,10,TimeUnit.SECONDS);
    }
}
